﻿layui.use(['form', 'laydate', 'layer'], function () {
    var form = layui.form;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var layer = layui.layer;
    var $ = layui.$;
    laydate.render({
        elem: '#measureDate'
    });

    // 绑定耳号
    function bindSheepEarNumber() {
        $.ajax({
            url: `http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesAllInfo`,
            type: 'get',
            dataType: 'json',
            success: function (res) {
                var enumData = res; // 直接使用返回的数据
                var select = $('#earNumber');

                $.each(enumData, function (index, item) {
                    if (item.sheepType == "后裔") {
                        // 使用正确的字段添加选项到下拉框中
                        var option = $('<option>').val(item.earNnumber).text(item.earNnumber);
                        select.append(option);
                    }
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    };
    // 提交事件
    form.on('submit(demo1)', function (data) {
        var formData = {
            bodyMeasurementId: $("[name='bodyMeasurementId']").val(),

            MeasureDate: $("#measureDate").val(),
            earNumber: $("#earNumber").val(),
            BodyMeasurementId: $("#bodyMeasurementId").val(),
            sheepBreed: $("#sheepBreed").val(),

            cottageId: $("#cottageId").val(),
            field: $("#field").val(),
            Height: $("#height").val(),
            BodyLength: $("#bodyLength").val(),
            ChestWidth: $("#chestWidth").val(),
            CannonCircumference: $("#cannonCircumference").val(),
            ScrotalCircumference: $("#scrotalCircumference").val(),
            BackfatThickness: $("#backfatThickness").val(),
            EyeMuscleArea: $("#eyeMuscleArea").val(),
            EyeMuscleWidth: $("#eyeMuscleWidth").val(),
            CreateBy: "张三",
            CreateDate: new Date(),
            UpdateBy: "李四",
            UpdateDate: new Date(),
        };

        // 发起Ajax请求更新数据
        $.ajax({
            url: 'http://10.31.60.18:8000//BreedingsSetRout/api/BodyMeasurement/UpdateMeasurement',
            type: 'PUT', // PUT请求
            data: JSON.stringify(formData), // 将数据转换为JSON格式
            contentType: 'application/json',
            success: function (response) {
                if (response.code == 200) {
                    layer.msg(response.msg, { icon: 1 });
                    setTimeout(function () {
                        location.href = '/Breedings/ShowBodyMeasurement';
                    }, 1000)
                } else {
                    layer.msg(response.msg, { icon: 2 });
                }
            },
            error: function (xhr, status, error) {
                console.error('Error occurred while updating data:', error);
                layer.alert('数据修改失败，请重试', {
                    title: '提示'
                });
            }
        });

        return false; // 阻止默认 form 提交
    });

    // 自定义函数，用于获取URL参数
    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }

    // 获取用户信息并反填到表单中
    function getBodyMeasurement() {
        //function getSheepWeighing() {
        var BodyMeasurementId = getUrlParam('BodyMeasurementId');

        $.ajax({
            url: `http://10.31.60.18:8000/BreedingsGetRout/api/BodyMeasurement/BackfillBodyMeasurement?BodyMeasurementId=${BodyMeasurementId}`,
            type: 'GET',
            success: function (response) {
                if (response.code === 200) {
                    var data = response.data;
                    $("#measureDate").val(data.measureDate.split('T')[0]);
                    $("#earNumber").val(data.earNumber);

                    $("#sheepBreed").val(data.sheepBreed);
                    $("#cottageId").val(data.cottageId);
                    $("#field").val(data.field);
                    $("#bodyMeasurementId").val(data.bodyMeasurementId);
                    $("#height").val(data.height);
                    $("#bodyLength").val(data.bodyLength);
                    $("#chestWidth").val(data.chestWidth);
                    $("#cannonCircumference").val(data.cannonCircumference);
                    $("#scrotalCircumference").val(data.scrotalCircumference);
                    $("#backfatThickness").val(data.backfatThickness);
                    $("#eyeMuscleArea").val(data.eyeMuscleArea);
                    $("#eyeMuscleWidth").val(data.eyeMuscleWidth);

                    // 重新渲染layui表单
                    form.render('select');
                } else {
                    console.log('Failed to fetch data. Server response:', response);
                }
            },
            error: function (xhr, status, error) {
                console.error('Error occurred while fetching data:', error);
            }
        });
    };

    $(function () {
        bindSheepEarNumber();
        setTimeout(function () {
            getBodyMeasurement();
        }, 60)
    })
});